<template>
    <view >
        <view class="section">
            <view class="section-title">球杆信息</view>
            <!-- 表单组件 -->
            <uni-forms :model="form" ref="formRef" :rules="rules" label-width="180rpx">
                <uni-forms-item required label="品牌名称" name="brandName" >
                    <uni-easyinput v-model="form.brandName" placeholder="例：奥秘/无" @blur="() => validateField('brandName')" />
                </uni-forms-item>
                <uni-forms-item required label="球杆名称" name="cueName">
                    <uni-easyinput type="text" v-model="form.cueName" placeholder="例：三国白龙台球杆" @blur="() => validateField('cueName')" />
                </uni-forms-item>
                <uni-forms-item required label="台球杆结构" name="cueStruc">
                    <uni-data-select
                        v-model="form.cueStruc"
                        :localdata="changeList"
                        @change="change"
                        placeholder="请选择台球杆结构"
                        @blur="() => validateField('cueStruc')"
                    ></uni-data-select>
                </uni-forms-item>
                <uni-forms-item required label="外观成色" name="useLevel">
                    <uni-data-select
                        v-model="form.useLevel"
                        :localdata="oldList"
                        @change="change"
                        placeholder="请选择外观成色"
                        @blur="() => validateField('useLevel')"
                    ></uni-data-select>
                </uni-forms-item>
                <uni-forms-item required label="购入价" name="transactionPrice">
                    <uni-easyinput type="text" v-model="form.transactionPrice" placeholder="例：15800元" @blur="() => validateField('transactionPrice')" />
                </uni-forms-item>
                <uni-forms-item required label="购买时间" name="purchaseDate">
                    <uni-datetime-picker type="date" placeholder="请输入购买时间" :clear-icon="false" v-model="form.purchaseDate" @maskClick="maskClick" @blur="() => validateField('purchaseDate')" />
                </uni-forms-item>
                <uni-forms-item label="是否手工杆" name="isManual">
                    <uni-data-select
                        v-model="form.isManual"
                        :localdata="typeList"
                        @change="change"
                        placeholder="请选择是否手工杆"
                    ></uni-data-select>
                </uni-forms-item>
                <uni-forms-item label="附加值" name="addedValue">
                    <uni-easyinput type="text" v-model="form.addedValue" placeholder="例：杆盒/配件/防伪"  />
                </uni-forms-item>
            </uni-forms>
            <view class="section-title">球杆图片</view>
            <view class="example-body">
                <uni-file-picker 
                    v-model="imageValue" 
                    file-mediatype="image" 
                    file-extname="png,jpg" 
                    mode="grid" 
                    :limit="5" 
                    title="最多选择5张图片"
                    @select="handleSelect"
                ></uni-file-picker>
            </view>
            <!-- 提交按钮 -->
            <view class="btn-wrap">
                <button class="index-title-btn" type="primary" clickable @click="submitForm">开始估杆</button>
            </view>
        </view>
    </view>
  </template>
  
  <script setup>
  import { ref } from 'vue'
  import { request,uploadFiles  } from '../utils/request'
  
  const formRef = ref()
  const imageValue = ref([]) // 绑定已选择文件列表
  const localImagePaths = ref([]) // 存储临时地址
  
  const form = ref({
    brandName: '',
    cueName: '',
    cueStruc: '',
    useLevel: '',
    transactionPrice: '',
    purchaseDate: '',
    isManual: '',
    addedValue: ''
  })
  const typeList = [
    { value: "是", text: "是" },
    { value: "否", text: "否" },
  ]
  const oldList = [
    { value: "全新未使用", text: "全新未使用" },
    { value: "99新", text: "99新" },
    { value: "95新", text: "95新" },
    { value:  "9新", text: "9新" },
    { value: "8新", text: "8新" },
    { value: '8新以下', text: '8新以下' }
  ]

  const changeList = [
    { value: "一体通杆", text: "一体通杆" },
    { value: "分体杆", text: "分体杆" },
  ]
  const frontDryYearList = [
    { value:  "1年以下" , text: "1年以下" },
    { value:  "1-3年", text: "1-3年" },
    { value: "3-5年", text: "3-5年" },
    { value: "5年以上", text: "5年以上" },
  ]
    const rules = {
        brandName: {
            rules: [
                { required: true, errorMessage: '请输入品牌名称', trigger: 'blur' }
            ]
        },
        cueName: {
            rules: [
                { required: true, errorMessage: '请输入球杆名称', trigger: 'blur' }
            ]
        },
        cueStruc: {
            rules: [
                { required: true, errorMessage: '请选择球杆结构', trigger: 'blur' }
            ]
        },
        useLevel: {
            rules: [
                { required: true, errorMessage: '请选择外观成色', trigger: 'blur' }
            ]
        },
        purchaseDate: {
            rules: [
                { required: true, errorMessage: '请输入购买时间', trigger: 'blur' }
            ]
        },
        transactionPrice: {
            rules: [
                { required: true, errorMessage: '请输入购入价', trigger: 'blur' }
            ]
        }
       
    }
 
    const maskClick = (e) => {
        console.log('maskClick事件:', e);
    }
    const validateField = (name) => {
        formRef.value?.validateField(name)
    }
    const handleSelect = (e) => {
        // 提取临时地址
        localImagePaths.value = e.tempFiles.map(file => file.file)
        console.log('临时地址数组:', localImagePaths.value)
    }
  const submitForm = () => {
    formRef.value.validate().then(async () => {
        // 校验通过
        uni.showLoading({ title: '提交中...' })
        try {
            await request({
            url: '/user/assess/submit',
            method: 'POST',
            data: form.value
        })
            .then(async (res) => {
                if (res.code === 200) {
                    const id = res.data
                    const uploadTasks = localImagePaths.value.map((item, index) => {
                        console.log('上传文件:', index == 0 ? 'true' : 'false')
                        return uploadFiles({
                            url: `/user/assess/upload/${id}`,
                            filePath: item.tempFilePath,
                            name: 'file',
                            formData: {
                                id,
                                cover: index == 0 ? 'true' : 'false',
                                file: item
                            },
                            header: {
                                'Content-Type': 'multipart/form-data'
                            }
                        })
                    })
                    // 等待所有上传完成
                    await Promise.all(uploadTasks);
                    uni.hideLoading()
                    form.value = {
                        brandName: '',
                        cueName: '',
                        cueStruc: '',
                        useLevel: '',
                        transactionPrice: '',
                        purchaseDate: '',
                        isManual: '',
                        addedValue: ''
                    }
                    localImagePaths.value = []
                    imageValue.value = []
                    uni.showToast({ title: '提交成功', icon: 'success', duration: 3000})
					uni.navigateTo({
						url: '/pages/index/result?id=' + id
					})
                } else {
                    uni.showToast({ title: res.data.message || '提交失败', icon: 'none', duration: 3000  })
                }
            }).catch((err) => {
                console.error('请求失败:', err)
                uni.showToast({ title: err.data.message || '提交失败', icon: 'none', duration: 3000  })
            })
        } catch (err) {
            console.log('验证失败', err);
            uni.hideLoading()
        } finally {
            uni.hideLoading()
        }
    }).catch((err) => {
        console.log('验证失败', err)
        uni.hideLoading()
    })
  }
  </script>
  
  <style scoped>
  .section {
    padding: 20rpx 40rpx 40rpx 40rpx;
  }
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
  }
  .btn-wrap {
    margin-top: 30rpx;
    display: flex;
    justify-content: center;
  }
   .index-title-btn{
        background: linear-gradient(to right, #45b5ff, #2b65f6);
		color: #fff;
		border-radius: 10rpx;
		height: 80rpx;
		line-height: 80rpx;
		width: 200px;
    }
    
  </style>
  